<template>
  <div class="contentView" v-loading="formLoading" :style="`height:${contentHeight}px`">
    <div class="routeHeader mb-5px">
      <!-- <el-button
        class="mr-5px"
        @click="submitForm"
        type="primary"
        v-hasPermi="['produce:course-welding:save']"
        :disabled="formLoading"
        >保 存</el-button
      > -->
      <el-button @click="goBack">关 闭</el-button>
    </div>
    <el-scrollbar :style="`height:${contentHeight - 63}px`">
      <p class="baseTitle">工单信息</p>
      <ContentWrap>
        <div class="disFlex">
          <div class="cell">
            <span>工单号：</span>
            <span>{{ formData.workTaskNumber }}</span>
          </div>
          <div class="cell">
            <span>产品编号：</span>
            <span>{{ formData.productNumber }}</span>
          </div>
          <div class="cell">
            <span>产品名称：</span>
            <span>{{ formData.productName }}</span>
          </div>
        </div>
        <div class="disFlex bg">
          <div class="cell">
            <span>部件编号：</span>
            <span>{{ formData.partNumber }}</span>
          </div>
          <div class="cell">
            <span>部件名称：</span>
            <span>{{ formData.partName }}</span>
          </div>
          <div class="cell">
            <span>图纸图号：</span>
            <span>{{ formData.drawingNumber }}</span>
          </div>
        </div>
        <div class="disFlex">
          <div class="cell">
            <span>计划数量：</span>
            <span>{{ formData.planQuantity }}</span>
          </div>
          <div class="cell">
            <span>完工数量：</span>
            <span>{{ formData.completeQuantity }}</span>
          </div>
          <div class="cell">
            <span>差异数量：</span>
            <span>{{ formData.differenceQuantity }}</span>
          </div>
        </div>
      </ContentWrap>
      <p class="baseTitle mt-10px mt-10px">生产任务</p>
      <el-table
        ref="singleTableRef"
        :data="productionTasksList"
        style="width: 100%"
        border
        :header-cell-style="headFirst"
        default-expand-all
        row-key="id"
      >
        <el-table-column type="index" label="序号" width="80" align="center" fixed="left" />
        <template v-for="(item, index) in productionTasksTitle" :key="index">
          <el-table-column
            :prop="item.val"
            :label="item.label"
            :min-width="item.width"
            :align="item.val == 'processPrice' ? 'right' : 'left'"
            :header-align="item.val == 'processPrice' ? 'right' : 'left'"
          >
            <template #default="scope">
              <template v-if="item.val == 'reportQuantity'">
                <el-input-number
                  controls-position="right"
                  :min="0"
                  v-model="scope.row[item.val]"
                  :disabled="[20, 40].includes(scope.row.dictStatus)"
                  v-if="
                    scope.row.dictReportWay === 10 ||
                    (scope.row.dictReportWay === 20 && scope.row.isChild)
                  "
                />
                <span v-else>{{ scope.row[item.val] }}</span>
              </template>
              <dict-tag v-else-if="item.val === 'dictProcessName'" type="craft_process_name" :value="scope.row.dictProcessName" />
              <!-- 处理进度下的展示 -->
              <template
                v-else-if="
                  ['planQuantity', 'completeQuantity', 'differenceQuantity'].includes(item.val)
                "
              >
                <!-- 进度 -->
                <template v-if="formData.dictReportWay == 20 && scope.row.isChild">
                  {{ formatNum(scope.row[item.val]) }}
                </template>
                <template v-else> {{ scope.row[item.val] }} </template>
              </template>
              <template v-else>
                <el-button
                  v-if="item.label == '图纸图号'"
                  type="primary"
                  link
                  @click="jumpPdfFile(scope.row[item.val],formData.productNumber)"
                  >{{ scope.row[item.val] }}</el-button
                >
                <span v-else>{{ scope.row[item.val] }}</span>
              </template>
            </template>
          </el-table-column>
        </template>

        <el-table-column
          label="操作"
          min-width="390"
          align="left"
          header-align="left"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              @click="reportingWork(scope.row)"
              link
              type="primary"
              size="small"
              v-hasPermi="['produce:course-welding:report']"
              v-if="
                (scope.row.dictReportWay === 10 ||
                  (scope.row.dictReportWay === 20 && scope.row.isChild)) &&
                ![20, 40].includes(scope.row.dictStatus)
              "
              >报工</el-button
            >
            <template
              v-if="
                scope.row.dictReportWay === 10 || (scope.row.dictReportWay && scope.row.hasChild)
              "
            >
              <el-button
                @click="showDrawingNumber(scope.row.drawingNumber)"
                link
                v-hasPermi="['produce:course-welding:drawing']"
                type="primary"
                size="small"
                >查看图纸</el-button
              >
              <el-button
                @click="showWorkingInstruction(scope.row)"
                link
                v-hasPermi="['produce:course-welding:workingInstruction']"
                type="primary"
                size="small"
                >查看作业指导书</el-button
              >
              <el-button
                type="primary"
                size="small"
                link
                v-hasPermi="['produce:course-welding:bom']"
                @click="openMaterial(scope.row.productNumber,scope.row.partNumber)"
                >查看物料清单</el-button
              >
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>

    <!-- 完工 -->
    <reportingWorkView ref="reportingWorkRef" @refresh="refreshData" />
    <!-- 查看作业指导书 -->
    <workingInstruction ref="workingInstructionRef" />
    <!-- 查看图纸 -->
    <drawingNumber ref="drawingNumberRef" />
    <!-- 物料清单 -->
    <material
      v-show="showMaterial"
      ref="materialRef"
      class="material"
      :style="`height:${contentHeight}px`"
      @closeView="showMaterial = false"
    />
  </div>
</template>
<script setup lang="ts">
  //import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import request from '@/config/axios'
  import * as CourseWeldingApi from '@/api/produce/processManagement/courseWelding'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import { jumpPdfFile } from '@/utils/formCreate'
  //报工
  import reportingWorkView from '../components/reportingWork.vue'
  //查看作业指导书
  import workingInstruction from '../components/workingInstruction.vue'
  //查看图纸
  import drawingNumber from '../components/drawingNumber.vue'
  //物料清单
  import material from '../components/material.vue'
  //const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗

  const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
  const formData = ref({})
  /**百分比转换 */
  const formatNum = (num: number) => {
    return `${parseFloat(num * 100)}%`
  }
  /**报工 */
  const reportingWorkRef = ref()
  const reportingWork = async (row: object) => {
    if (!row['processPrice']) {
      const res = await getProcessingUnitPrice({
        productNumber: row['productNumber'],
        partNumber: row['partNumber'],
        dictProcessName: row['dictProcessName']
      })
      if (res.code == 1100000113) {
        message.notifyError(res.msg)
        return
      }
      row.processPrice = res.unitPrice
    }
    if (row['dictReportWay'] === 10) {
      if (parseFloat(row['reportQuantity']) > parseFloat(row['differenceQuantity'])) {
        message.notifyError('报工数量不能大于差异数量')
        return
      }
      if (!row['reportQuantity']) {
        message.notifyError('请输入报工数量')
        return
      }
    } else {
      if (parseFloat(row['reportQuantity']) / 100 > parseFloat(row['differenceQuantity'])) {
        message.notifyError('报工进度不能大于差异进度')
        return
      }
      if (!row['reportQuantity']) {
        message.notifyError('请输入报工进度')
        return
      }
    }
    console.log('row', row)
    reportingWorkRef.value.open(row, 'produce/course-welding/workTime', formData.value.planQuantity)
  }
  /**获取加工单价 */
  const getProcessingUnitPrice = async (params: object) => {
    const res = await request.get({ url: '/config/wage-quotations-confirmed-task/getPrice', params })
    return res
  }
  // 打开物料清单
  const showMaterial = ref(false)
  const materialRef = ref()
  const openMaterial = (productNumber: string,partNumber: string) => {
    showMaterial.value = true
    materialRef.value!.getData(productNumber,partNumber)
  }
  /**查看作业指导书 */
  const workingInstructionRef = ref()
  const showWorkingInstruction = (data) => {
    workingInstructionRef.value.open(data)
  }
  //查看图纸
  const drawingNumberRef = ref()
  const showDrawingNumber = (drawingNumber) => {
    drawingNumberRef.value.open(drawingNumber)
  }

  /**返回 */
  const tagsViewStore = useTagsViewStore()
  const route = useRouter() // 路由
  const goBack = async () => {
    //获取当前路由并删除tagView
    tagsViewStore.delView(route.currentRoute.value)
    //跳转列表页
    route.push({
      path: '/produce/produce/processManagement/courseWelding'
    })
  }
  /** 提交表单 */
  // const submitForm = async () => {
  //   formLoading.value = true
  //   const data = JSON.parse(JSON.stringify(formData.value))
  //   try {
  //     await CourseWeldingApi.updateCourseWelding(data)
  //     message.success(t('common.updateSuccess'))
  //     refreshData()
  //   } finally {
  //     formLoading.value = false
  //   }
  // }

  //生产任务表头
  const productionTasksTitle = ref([
    {
      label: '工序名称',
      val: 'dictProcessName',
      width: 250
    },
    {
      label: '细部工序',
      val: 'subProcessName',
      width: 200
    },
    {
      label: '工单号/任务单号',
      val: 'workTaskNumber',
      width: 250
    },
    {
      label: '产品编号',
      val: 'productNumber',
      width: 200
    },
    {
      label: '产品名称',
      val: 'productName',
      width: 200
    },
    {
      label: '型号规格',
      val: 'productStandard',
      width: 200
    },
    {
      label: '订单数量',
      val: 'orderQuantity',
      width: 200
    },
    {
      label: '编号',
      val: 'code',
      width: 200
    },
    {
      label: '部件编号',
      val: 'partNumber',
      width: 200
    },
    {
      label: '部件名称',
      val: 'partName',
      width: 200
    },
    {
      label: '图纸图号',
      val: 'drawingNumber',
      width: 200
    },
    {
      label: '部件规格',
      val: 'partSpecification',
      width: 200
    },
    {
      label: '材质',
      val: 'material',
      width: 200
    },
    {
      label: '规格',
      val: 'specification',
      width: 200
    },
    {
      label: '净尺寸(长)',
      val: 'netSizeLength',
      width: 200
    },
    {
      label: '净尺寸(宽)',
      val: 'netSizeWidth',
      width: 200
    },
    {
      label: '下料尺寸(长)',
      val: 'cuttingSizeLength',
      width: 200
    },
    {
      label: '下料尺寸(宽)',
      val: 'cuttingSizeWidth',
      width: 200
    },
    {
      label: '机加工序',
      val: 'dictMachiningProcess',
      width: 200
    },
    {
      label: '计划数量',
      val: 'planQuantity',
      width: 200
    },
    {
      label: '报工数量/报工进度',
      val: 'reportQuantity',
      width: 200
    },
    {
      label: '完工数量',
      val: 'completeQuantity',
      width: 200
    },
    {
      label: '差异数量',
      val: 'differenceQuantity',
      width: 200
    },
    {
      label: '加工单价',
      val: 'processPrice',
      width: 200
    },
    {
      label: '生产班组',
      val: 'productionTeam',
      width: 200
    },
    {
      label: '设备名称',
      val: 'deviceName',
      width: 200
    },
    {
      label: '设备编码',
      val: 'deviceCode',
      width: 200
    },
    {
      label: '作业者',
      val: 'operator',
      width: 200
    }
  ])
  // 获得id
  const { query } = useRoute() // 路由的查询
  const contentHeight = ref(0)
  const productionTasksList = ref([])
  const refreshData = async () => {
    console.log(111111111)
    formLoading.value = true
    if (query.id) {
      formData.value = await CourseWeldingApi.getCourseWelding(query.id)
      if (formData.value.children.length) {
        formData.value.hasChild = true
      }
      formData.value.children.map((item) => {
        item.isChild = true
        return item
      })
      formData.value.parentIndex = 1
      productionTasksList.value = [formData.value]
      contentHeight.value = document.body.clientHeight - 127
    }
    formLoading.value = false
  }
  // 合并编号
  const headFirst = ({ rowIndex }) => {
    if (rowIndex === 1) {
      return { display: 'none' }
    }
  }
  onMounted(() => {
    refreshData()
  })
</script>
<style scoped lang="scss">
  .contentView {
    padding: 10px;
    background: #fff;
    position: relative;

    .material {
      width: 100%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 99;
    }

    .disFlex {
      display: flex;
    }

    .cell {
      width: 33%;
      height: 60px;
      line-height: 60px;
      padding-left: 10px;
      box-sizing: border-box;
    }

    .bg {
      background-color: #f0f1f5;
    }
  }

  .tableView {
    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
      cursor: default;

      .el-input__inner {
        cursor: default !important;
        text-align: left;
      }
    }
  }
</style>